package com.hardydou.common.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.hardydou.framework.exception.AppExceptionHandler;
import com.hardydou.system.model.LoginUserDetails;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;

/**
 * @author ：hardy
 * @description：通用控制器
 * @date ：Created in 2020-03-04
 * @Copyright ：Hardydou.com
 */
public abstract class BaseController {

    /**
     * 获取 session
     *
     * @return
     */
    protected static HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 获取 HttpServletRequest
     *
     * @return
     */
    protected static HttpServletRequest getRequest() {
        return getServletRequestAttributes().getRequest();
    }

    /**
     * 获取  HttpServletResponse
     *
     * @return
     */
    protected static HttpServletResponse getResponse() {
        return getServletRequestAttributes().getResponse();
    }

    protected static ServletRequestAttributes getServletRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    protected LoginUserDetails getLoginUserDetails() {
        return (LoginUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }


    /***
     * 主模块名称
     * @return
     */
    public abstract String getModel();

    /***
     * 子模块名称
     * @see #page(String)
     * @return
     */
    public abstract String getSubModel();

    private String path(String dir) {
        if (StrUtil.isBlank(dir)) {
            return "";
        }
        return dir + File.separator;
    }

    protected String page(String filename) {
        return path(getModel()) + path(getSubModel()) + filename;
    }
}
